using RuoYi.Common.Utils;
using RuoYi.System.Repositories;

namespace RuoYi.System.Services;

/// <summary>
/// 字典数据表服务
/// </summary>
public class SysDictDataService : BaseService<SysDictData, SysDictDataDto>, ITransient
{
    private readonly ILogger<SysDictDataService> _logger;
    private readonly SysDictDataRepository _sysDictDataRepository;

    public SysDictDataService(ILogger<SysDictDataService> logger,
        SysDictDataRepository sysDictDataRepository)
    {
        BaseRepo = sysDictDataRepository;

        _logger = logger;
        _sysDictDataRepository = sysDictDataRepository;
    }

    /// <summary>
    /// 根据字典数据ID查询信息
    /// </summary>
    /// <param name="id">字典数据ID</param>
    /// <returns></returns>
    public async Task<SysDictData> GetSysDictDataByIdAsync(long id)
    {
        var entity = await base.FirstOrDefaultAsync(e => e.DictCode == id);
        return entity;
    }

    /// <summary>
    /// 新增保存字典数据信息
    /// </summary>
    public async Task<bool> InsertDictDataAsync(SysDictDataDto data)
    {
        bool success = await _sysDictDataRepository.InsertAsync(data);
        if (success)
        {
            List<SysDictData> dictDatas = await _sysDictDataRepository.GetDictDataByTypeAsync(data.DictType);
            DictUtils.SetDictCache(data.DictType, dictDatas);
        }
        return success;
    }

    /// <summary>
    /// 修改保存字典数据信息
    /// </summary>
    public async Task<int> UpdateDictDataAsync(SysDictDataDto data)
    {
        int row = await _sysDictDataRepository.UpdateAsync(data);
        if (row > 0)
        {
            List<SysDictData> dictDatas = await _sysDictDataRepository.GetDictDataByTypeAsync(data.DictType);
            DictUtils.SetDictCache(data.DictType, dictDatas);
        }
        return row;
    }

    /// <summary>
    /// 批量删除字典数据信息
    /// </summary>
    public async Task DeleteDictDataByIdsAsync(long[] ids)
    {
        foreach (long id in ids)
        {
            SysDictData data = await GetSysDictDataByIdAsync(id);
            await _sysDictDataRepository.DeleteAsync(id);
            List<SysDictData> dictDatas = await _sysDictDataRepository.GetDictDataByTypeAsync(data.DictType);
            DictUtils.SetDictCache(data.DictType, dictDatas);
        }
    }
}